import { Component, OnInit } from '@angular/core';
import { DataVisualizationService } from '../dataVisualization.service';
import { MESSAGE_CHANNEL, SYSTEM_EVENT } from 'app/app.constants';
import { BullySubjectService, ToolsService } from 'app/shared/service';
import { Router } from '@angular/router';
import { AlarmService } from 'app/pages/traffic-management/traffic-alert/alarm.service';

@Component({
    selector: 'itmp-overall',
    templateUrl: './overall.component.html',
    styleUrls: ['./overall.component.css']
})
export class OverallComponent implements OnInit {
    listOfData: any;
    renderHeader: any;
    sort = 'desc';
    dashboardData: any;
    monthArr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    constructor(
        private ds: DataVisualizationService,
        private bully: BullySubjectService,
        private router: Router,
        private als: AlarmService,
        private tools: ToolsService
    ) {}

    ngOnInit() {
        this.renderHeader = [
            {
                name: 'ID',
                key: null,
                value: 'ID'
            },
            {
                name: 'Description',
                key: null,
                value: 'Description'
            },
            {
                name: 'Data/Time',
                key: null,
                value: 'DateTime'
            },
            {
                name: 'Location',
                key: null,
                value: 'Location'
            },
            {
                name: 'Status',
                key: null,
                value: 'Status'
            },
            {
                name: 'View_Details',
                key: null,
                value: 'ViewDetails'
            }
        ];
        this.listOfData = [];
        this.dashboardData = {
            TotalIncedents: {
                total: null,
                lastUpdated: null,
                monthlyUpdate: null
            },
            TotalEvents: {
                total: null,
                lastUpdated: null,
                monthlyUpdate: null
            },
            period: {
                startTime: 12,
                startUnit: 12 >= 12 ? 'pm' : 'am',
                endTime: 14,
                endUnit: 14 >= 12 ? 'pm' : 'am',
                lastUpdated: this.ds.changeDate(1531192070245, 1, true),
                monthlyUpdate: null
            },
            weather: {
                deg: 38,
                area: 'Quang Ninh',
                ico: '',
                lastUpdated: this.ds.changeDate(1531192070245, 1, true),
                monthlyUpdate: null
            }
        };
        this._getData();
        // 每两分钟刷新一次
        setInterval(() => {
            this._getData();
        }, 1000 * 60 * 2);
    }

    _getData() {
        this.ds.getIncidentAnalyticsReport(203, `sort=${this.sort}`).subscribe(res => {
            this.listOfData = [];
            if (res.messagecode === '000000') {
                const newData = [];
                res.data.forEach(item => {
                    switch (item.selectedType) {
                        case 'recentOperationalNotification': {
                            const formatTime = item.DateTime.substring(0, 19);
                            newData.push({ ...item, eqtType: 1, DateTime: formatTime });
                            break;
                        }
                        case 'period': {
                            this.dashboardData[item.selectedType]['lastUpdated'] = this.ds.changeDate(+item.lastUpdated * 1000, 1, true);
                            const date = new Date(+item.MonthlyUpdates * 1000);
                            this.dashboardData[item.selectedType]['monthlyUpdate'] =
                                this.monthArr[date.getMonth()] + ' ' + date.getFullYear();
                            if (item.timeLag) {
                                const timeList = ['start', 'end'];
                                timeList.forEach((data, indx) => {
                                    this.dashboardData[item.selectedType][data + 'Time'] = item.timeLag.split('~')[indx];
                                    this.dashboardData[item.selectedType][data + 'Unit'] =
                                        Number(item.timeLag.split('~')[indx].split(':')[0]) >= 12 ? 'pm' : 'am';
                                });
                            }
                            break;
                        }
                        // tslint:disable-next-line: no-switch-case-fall-through
                        default: {
                            this.dashboardData[item.selectedType]['total'] = item.total;
                            this.dashboardData[item.selectedType]['lastUpdated'] = this.ds.changeDate(+item.lastUpdated * 1000, 1, true);
                            const date = new Date(+item.MonthlyUpdates * 1000);
                            this.dashboardData[item.selectedType]['monthlyUpdate'] =
                                this.monthArr[date.getMonth()] + ' ' + date.getFullYear();
                            break;
                        }
                    }
                });
                this.listOfData = newData.slice(0, 10);
            }
        });
        this.ds.getWeather(21.160397157837025, 107.27915929880047).subscribe(res => {
            const C = (Math.round(res.main.temp * 100) - Math.round(273.15 * 100)) / 100;
            const date = new Date();
            this.dashboardData.weather.deg = C;
            this.dashboardData.weather.ico = res.weather[0].icon;
            this.dashboardData.weather.lastUpdated = this.ds.changeDate(date.getTime(), 1, true);
            this.dashboardData.weather.monthlyUpdate = this.monthArr[date.getMonth()] + ' ' + date.getFullYear();
        });
    }

    // 点击列表
    clickTR(data) {}

    setSort(e) {
        this.sort = e;
        this._getData();
    }

    // 定位
    setPosition(data) {
        const bully = {
            type: SYSTEM_EVENT.ALERT_POSITION,
            data
        };
        this.bully.registerBroadcastSend(MESSAGE_CHANNEL.CCM_CHANNEL, bully);
    }

    locationAlert(id: string) {
        const params = {
            condition: {
                ackBy: null,
                ackTime: {
                    startTime: null,
                    endTime: null
                },
                ackValue: null,
                alertID: id,
                alertSource: null,
                detectionTime: {
                    endTime: null,
                    startTime: null
                },
                roadName: null,
                zoneID: null,
                description: null,
                zoneList: []
            },
            pageNum: 1,
            pageSize: 10
        };
        this.als.getTrafficAlert(params).subscribe(res => {
            const alert = this.tools.calc(res, 'data.list.0', null);
            if (!alert) {
                return;
            }
            this.setPosition(alert);
        });
    }
}
